package com.k.ums.security;

import com.k.ums.model.LoginUser;
import com.k.ums.model.SysUser;
import com.k.ums.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @Author: kt
 * @CreateTime: 2022/1/27
 */
@Component
@Slf4j
public class UmsUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.selectUserByName(username);
        if (sysUser == null) {
            log.info("用户:" + username + "不存在");
            throw new UsernameNotFoundException("用户:" + username + "不存在");
        }
        return this.createUserDetails(sysUser);
    }

    private UserDetails createUserDetails(SysUser user) {
        return new LoginUser(user);
    }
}
